﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using SO.SharePoint.Utilities.Logging;

namespace SO.SharePoint.Utilities
{
    public class Utility
    {
        public static string GetStringFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                if (item[fieldId] != null)
                    return item[fieldId].ToString();
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return string.Empty;
            }
        }

        public static bool GetBoolFromSPListItem(SPListItem item, Guid fieldId, bool defaultValue)
        {
            try
            {
                if (item[fieldId] != null)
                    return bool.Parse(item[fieldId].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static bool GetBoolFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                if (item[fieldName] != null)
                    return bool.Parse(item[fieldName].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static bool GetBoolFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                if (item[fieldId] != null)
                    return bool.Parse(item[fieldId].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static bool GetBoolFromSPListItem(SPListItem item, string fieldName, bool defaultValue)
        {
            try
            {
                if (item[fieldName] != null)
                    return bool.Parse(item[fieldName].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static int GetIntFromSPListItem(SPListItem item, Guid fieldId, int defaultValue)
        {
            try
            {
                if (item[fieldId] != null)
                    return int.Parse(item[fieldId].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static int GetIntFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                if (item[fieldId] != null)
                    return int.Parse(item[fieldId].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static double GetDoubleFromSPListItem(SPListItem item, Guid fieldId, double defaultValue)
        {
            try
            {
                if (item[fieldId] != null)
                    return double.Parse(item[fieldId].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static double GetDoubleFromSPListItem(SPListItem item, string fieldName, double defaultValue)
        {
            try
            {
                if (item[fieldName] != null)
                    return double.Parse(item[fieldName].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static double GetDoubleFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                if (item[fieldName] != null)
                    return double.Parse(item[fieldName].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static DateTime GetDateTimeFromSPListItem(SPListItem item, Guid fieldId, DateTime defaultValue)
        {
            try
            {
                if (item[fieldId] != null)
                    return DateTime.Parse(item[fieldId].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static DateTime GetDateTimeFromSPListItem(SPListItem item, string fieldName, DateTime defaultValue)
        {
            try
            {
                if (item[fieldName] != null)
                    return DateTime.Parse(item[fieldName].ToString());
                else
                    return defaultValue;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return defaultValue;
            }
        }

        public static DateTime GetDateTimeFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                if (item[fieldName] != null)
                    return DateTime.Parse(item[fieldName].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static DateTime GetDateTimeFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                if (item[fieldId] != null)
                    return DateTime.Parse(item[fieldId].ToString());
                else
                    throw new NullReferenceException();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static DateTime? GetNDateTimeFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                if (item[fieldName] != null)
                    return DateTime.Parse(item[fieldName].ToString()) as DateTime?;
                else
                    return null;
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static DateTime? GetNDateTimeFromSPListItem(SPListItem item, Guid fieldid)
        {
            try
            {
                if (item[fieldid] != null)
                    return DateTime.Parse(item[fieldid].ToString()) as DateTime?;
                else
                    return null;
            }
            catch (Exception ex)
            {
                throw new Exception("Error while parsing", ex);
            }
        }

        public static string GetStringFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                if (item[fieldName] != null)
                {
                    return item[fieldName].ToString();
                }
                else
                {
                    foreach (SPField field in item.Fields)
                    {
                        if ((field.StaticName == fieldName) || (field.InternalName == fieldName))
                        {
                            return GetStringFromSPListItem(item, field.Id);
                        }
                    }
                }                

                return string.Empty;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return string.Empty;
            }
        }

        public static string StripHTMLfromText(string htmlString)
        {
            string pattern = @"<(.|\n)*?>";
            return Regex.Replace(htmlString, pattern, string.Empty);
        }

        public static string GetUrlOnSite(string fullQueryString, string relativeUrl)
        {
            try
            {
                int pos = fullQueryString.LastIndexOf('/');
                string url = string.Empty;
                if (pos > 0)
                {
                    url = fullQueryString.Substring(0, pos+1);
                }
                else
                {
                    url = fullQueryString;
                }

                if (relativeUrl.StartsWith("/"))
                {
                    relativeUrl = relativeUrl.Substring(1, relativeUrl.Length - 1);
                }

                url = string.Concat(url, relativeUrl);
                return url;
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return string.Empty;
            }
        }

        public static string GetUrlOnSite(SPWeb web, string relativeUrl)
        {
            try
            {
                string webUrl = web.Url;

                if (!webUrl.EndsWith("/"))
                {
                    webUrl = string.Concat(webUrl, "/");
                }

                if (relativeUrl.StartsWith("/"))
                {
                    relativeUrl = relativeUrl.Substring(1, relativeUrl.Length - 1);
                }

                return string.Concat(webUrl, relativeUrl);
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return string.Empty;
            }
        }

        public static SPWeb GetWebFromAbsoluteUri(string absoluteUri)
        {
            try
            {
                SPSite site = new SPSite(absoluteUri);
                string siteUrl = absoluteUri.Substring(site.Url.Length, absoluteUri.Length - site.Url.Length);
                return site.OpenWeb(siteUrl);
            }
            catch (Exception ex)
            {
                Logging.Logging.WriteException(ex);
                return null;
            }
        }

        public static string GetDisplayNameByFieldGuid(string listName, Guid fieldId)
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                SPList list = web.Lists[listName];
                if (list != null)
                {
                    if (list.Fields[fieldId] != null)
                    {
                        return list.Fields[fieldId].InternalName;
                    }
                }

                return string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static void ShowSharePointNotification(Page page, string text)
        {
            //build up javascript to inject at the tail end of the page 
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("<script>");

            //First wait until the SP.js is loaded, otherwise the notification doesn’t work 
            //gets an null reference exception 
            stringBuilder.AppendLine("ExecuteOrDelayUntilScriptLoaded(ShowNotification, \"sp.js\");");

            stringBuilder.AppendLine("function ShowNotification()");
            stringBuilder.AppendLine("{");
            stringBuilder.AppendLine(string.Format("SP.UI.Notify.addNotification(\"{0}\");", text));
            stringBuilder.AppendLine("}");

            stringBuilder.AppendLine("</script>");

            //add to the page 
            page.Controls.Add(new LiteralControl(stringBuilder.ToString()));
        }

        public static void ShowSharePointStatus(Page page, string text, string color)
        {
            //build up javascript to inject at the tail end of the page 
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("<script>");

            //First wait until the SP.js is loaded, otherwise the notification doesn’t work 
            //gets an null reference exception 
            stringBuilder.AppendLine("ExecuteOrDelayUntilScriptLoaded(ShowStatus, \"sp.js\");");

            stringBuilder.AppendLine("function ShowStatus()");
            stringBuilder.AppendLine("{");
            stringBuilder.AppendLine(string.Format("var statusId = SP.UI.Status.addStatus('{0}');", text));
            stringBuilder.AppendLine(string.Format("SP.UI.Status.setStatusPriColor(statusId, '{0}');", color));
            stringBuilder.AppendLine("}");

            stringBuilder.AppendLine("</script>");

            //add to the page 
            page.Controls.Add(new LiteralControl(stringBuilder.ToString()));
        }

        public static SPUser GetSPUserFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                SPFieldUser userField = item.Fields[fieldId] as SPFieldUser;

                if ((userField != null) && (item[fieldId] != null))
                {
                    SPFieldUserValue fieldValue = userField.GetFieldValue(item[fieldId].ToString()) as SPFieldUserValue;

                    if (fieldValue != null)
                    {
                        return fieldValue.User;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing item", ex);
            }
        }

        public static SPUser GetSPUserFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                SPFieldUser userField = item.Fields[fieldName] as SPFieldUser;

                if ((userField != null) && (item[fieldName] != null))
                {
                    SPFieldUserValue fieldValue = userField.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValue;

                    if (fieldValue != null)
                    {
                        return fieldValue.User;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing item", ex);
            }
        }

        public static List<SPUser> GetSPUserMultiFromSPListItem(SPListItem item, string fieldName)
        {
            try
            {
                SPFieldUser userField = item.Fields[fieldName] as SPFieldUser;

                if ((userField != null) && (item[fieldName] != null))
                {
                    SPFieldUserValueCollection fieldValueCollection = userField.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValueCollection;

                    if (fieldValueCollection != null)
                    {
                        List<SPUser> userList = new List<SPUser>();

                        foreach (SPFieldUserValue val in fieldValueCollection)
                        {
                            userList.Add(val.User);
                        }

                        return userList;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing item", ex);
            }
        }

        public static List<SPUser> GetSPUserMultiFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                SPFieldUser userField = item.Fields[fieldId] as SPFieldUser;

                if ((userField != null) && (item[fieldId] != null))
                {
                    SPFieldUserValueCollection fieldValueCollection = userField.GetFieldValue(item[fieldId].ToString()) as SPFieldUserValueCollection;

                    if (fieldValueCollection != null)
                    {
                        List<SPUser> userList = new List<SPUser>();

                        foreach (SPFieldUserValue val in fieldValueCollection)
                        {
                            userList.Add(val.User);
                        }

                        return userList;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing item", ex);
            }
        }

        public static string[] GetStringArrayFromSPListItem(SPListItem item, Guid fieldId)
        {
            try
            {
                SPFieldMultiChoice choiceField = item.Fields[fieldId] as SPFieldMultiChoice;
                if ((choiceField != null) && (item[fieldId] != null))
                {
                    SPFieldMultiChoiceValue fieldValue = new SPFieldMultiChoiceValue(item[fieldId].ToString());

                    if (fieldValue != null)
                    {
                        string[] res = new string[fieldValue.Count];

                        for (int i = 0; i <= fieldValue.Count - 1; i++)
                        {
                            res[i] = fieldValue[i].ToString();
                        }

                        return res;
                    }
                    else
                    {
                        throw new Exception("Field Value is null");
                    }
                }
                else
                {
                    return new string[0];
                    //throw new Exception("Field is null or empty");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error parsing item", ex);
            }
        }
    }
}
